package com.sdr.tackvideo.tackvideo;

import android.app.Activity;
import android.media.MediaPlayer;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;

/**
 * Created by Administrator on 2017/5/17.
 */

public class PreView implements SHCallBack.SHCallbackListener {
    private Activity mActivity;
    private SurfaceView mSurfaceView;
    private SurfaceHolder mHolder;

    private SHCallBack mCallBack;

    public PreView(Activity activity, SurfaceView surfaceView) {
        mActivity = activity;
        mSurfaceView = surfaceView;
        mHolder = surfaceView.getHolder();
        mCallBack = new SHCallBack(this);
    }

    private String videoPath;

    public String getVideoPath() {
        return videoPath;
    }

    public void setVideoPath(String videoPath) {
        this.videoPath = videoPath;
    }

    public void init() {
        mHolder.removeCallback(mCallBack);
        mHolder.addCallback(mCallBack);
    }


    private MediaPlayer mMediaPlayer;

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
        }
        mMediaPlayer.reset();
        try {
            mMediaPlayer.setDataSource(getVideoPath());
            mMediaPlayer.setDisplay(mHolder);
            mMediaPlayer.setLooping(true);
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
}
